package com.cloudkinto.service.file.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.entity.FileDo;
import com.cloudkinto.entity.FileMoreDo;
import com.cloudkinto.dao.FileMoreDao;
import com.cloudkinto.service.file.FileMoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.file.vo.FileRes;
import com.cloudkinto.service.operate.OperateRecordService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2022-11-22
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FileMoreServiceImpl extends ServiceImpl<FileMoreDao, FileMoreDo> implements FileMoreService {
    @Autowired
    private FileMoreDao dao;
    @Autowired
    private FileService fileService;
    @Autowired
    private OperateRecordService operateRecordService;


    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        FileMoreDo entityDo = new FileMoreDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(FileMoreDo entityDo, Long userId) {
        entityDo.setCreateTime(new Date());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(FileMoreDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*FileMoreDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(FileMoreDo entityDo, Long userId) {

    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(FileMoreDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        FileMoreDo entityDo = dao.selectById(id);
        Long fileId = entityDo.getFileId();
        FileDo fileDo = fileService.getById(fileId);
        int result = dao.deleteById(id);
        if (result > 0) {
            fileService.deleteFile(fileId);
        }
        //操作日志
        if (StaticDict.File_Type.RepairAttach.getValue().equals(entityDo.getType())) {
            operateRecordService.operateAddRecordAndValue(StaticDict.Order_Repair_Operate_Type.OrderRepair_Delete_Attach.getValue(), fileDo == null ? "!!!" : fileDo.getFileName(), entityDo.getMailId(), userId, 9);
        } else if (StaticDict.File_Type.RepairPic.getValue().equals(entityDo.getType())) {
            operateRecordService.operateAddRecordAndValue(StaticDict.Order_Repair_Operate_Type.OrderRepair_Delete_RepairPic.getValue(), fileDo == null ? "!!!" : fileDo.getFileName(), entityDo.getMailId(), userId, 9);
        }
        return result;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(FileMoreDo entityDo, Long userId) {
    }

    @Override
    public Object detail(Long id) {
        FileMoreDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<FileMoreDo> wrapper = queryBuild(map);
        List<FileMoreDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FileMoreDo> wrapper = queryBuild(map);
        IPage<FileMoreDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<FileMoreDo> list) {
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<FileMoreDo> pageInit(Map<String, String> map) {
        IPage<FileMoreDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FileMoreDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FileMoreDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }

    @Override
    public List<FileRes> getFileList(Long id, String type) {
        List<FileRes> list = new ArrayList<>();

        List<FileMoreDo> picFileList = dao.selectList(new LambdaQueryWrapper<FileMoreDo>().eq(FileMoreDo::getMailId, id).eq(FileMoreDo::getType, type));
        for (FileMoreDo picDo : picFileList) {
            FileRes fileRes = new FileRes();
            fileRes.setId(picDo.getId());
            fileRes.setFileId(picDo.getFileId());
            FileDo fileDo = fileService.getById(picDo.getFileId());
            if (fileDo == null) {
                continue;
            }
            fileRes.setFileName(fileDo.getFileName());
            fileRes.setFileSuffix(fileDo.getFileSuffix());
            fileRes.setUrl(fileService.getFilePath(picDo.getFileId()));
            list.add(fileRes);
        }
        return list;
    }

    /**
     * 附件一对多 插入
     *
     * @param fileIdList
     * @param id
     * @param type
     */
    @Override
    public void insertFileMoreList(List<Long> fileIdList, Long id, String type, Long userId) {
        if (fileIdList == null || fileIdList.size() == 0) {
            return;
        }
        StringBuilder fileName = new StringBuilder();
        fileIdList.forEach(fileId -> {
            FileMoreDo fileMoreDo = dao.selectOne(new LambdaQueryWrapper<FileMoreDo>()
                    .eq(FileMoreDo::getType, type).eq(FileMoreDo::getFileId, fileId).last(" order by id desc limit 1"));
            if (fileMoreDo == null) {
                fileMoreDo = new FileMoreDo();
                fileMoreDo.setMailId(id);
                fileMoreDo.setType(type);
                fileMoreDo.setFileId(fileId);
                fileMoreDo.setCreateTime(new Date());
                dao.insert(fileMoreDo);

                FileDo fileDo = fileService.getById(fileId);
                if (fileDo != null) {
                    if (fileName.length() > 0) {
                        fileName.append(",");
                    }
                    fileName.append(fileDo.getFileName());
                }
            }
            fileService.uploadFile(fileId);
        });
        if (StaticDict.File_Type.RepairAttach.getValue().equals(type)) {
            operateRecordService.operateAddRecordAndValue(StaticDict.Order_Repair_Operate_Type.OrderRepair_Upload_Attach.getValue(), fileName.toString(), id, userId, 9);
        } else if (StaticDict.File_Type.RepairPic.getValue().equals(type)) {
            operateRecordService.operateAddRecordAndValue(StaticDict.Order_Repair_Operate_Type.OrderRepair_Upload_RepairPic.getValue(), fileName.toString(), id, userId, 9);
        }

    }


    @Override
    public void insertFileMoreList(List<Long> fileIdList, Long id, String type, String tips, Long userId) {
        List<FileMoreDo> oldFileId = dao.selectList(new LambdaQueryWrapper<FileMoreDo>().eq(FileMoreDo::getType, type).eq(FileMoreDo::getMailId, id));

        for (int i = 0; i < oldFileId.size(); i++) {
            FileMoreDo fileMoreDo = oldFileId.get(i);
            if (!fileIdList.contains(fileMoreDo.getFileId())) {
                //不包含就删除
                dao.deleteById(fileMoreDo.getId());
                oldFileId.remove(i);
                i--;
            }
        }
        this.insertFileMoreList(fileIdList, id, type, userId);
    }


    @Override
    public void dealFileList(List<FileRes> fileList, Long id, String type, Long userId) {
        if (fileList != null) {
            List<Long> fileId = fileList.stream().filter(i -> i.getId() == null).map(FileRes::getFileId).collect(Collectors.toList());
            this.insertFileMoreList(fileId, id, type, userId);
        }
    }

}
